<template>
  <div class="app-container">
      <el-row :gutter="25">
        <el-col :span="25" :xs="24">
          <el-form :model="conditions" ref="queryForm" size="small" :inline="true" label-width="68px">
            <el-form-item label="用户姓名" prop="name">
              <el-input placeholder="请输入姓名" v-model="conditions.name" clearable class="search-input"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" prop="sex">
              <el-select v-model="conditions.sex" clearable placeholder="请选择性别" class="search-select">
                <el-option label="男" value="男"></el-option>
                <el-option label="女" value="女"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="用户状态" prop="status">
              <el-select v-model="conditions.work_status" clearable placeholder="请选择工作状态" class="search-select">
                <el-option label="已工作" value="已工作"></el-option>
                <el-option label="未工作" value="未工作"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" size="mini" icon="el-icon-search" @click="search" class="search-button">搜索</el-button>
              <el-button type="info" size="mini" icon="el-icon-refresh" @click="reset" class="search-button">重置</el-button>
              <el-button type="primary" plain size="mini" icon="el-icon-user" @click="insert" class="search-button">新增用户</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

    <div class="tableRow">
      <el-table :data="userList.records" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" width="100" label="编号" align="center"></el-table-column>
        <el-table-column label="头像" width="80" align="center">
          <template slot-scope="props">
            <el-avatar :size="50" :src="props.row.user_image"></el-avatar>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="姓名" align="center">
          <template slot-scope="scope">
            <el-popover trigger="hover" placement="top">
              <p>姓名: {{ scope.row.name }}</p>
              <p>创建时间: {{ scope.row.create_time }}</p>
              <div slot="reference" class="name-wrapper">
                <el-tag size="medium">{{ scope.row.name }}</el-tag>
              </div>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column prop="username" label="账号" align="center">
        </el-table-column>
        <el-table-column prop="phone_number" label="手机号" width="140" align="center">
        </el-table-column>
        <el-table-column prop="address" label="地址" align="center">
        </el-table-column>
        <el-table-column prop="sex" label="性别" align="center">
        </el-table-column>
        <el-table-column prop="age" label="年龄" align="center">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="200" align="center">
        </el-table-column>
        <el-table-column label="创建时间" width="180" align="center">
          <template slot-scope="scope">
            <i class="el-icon-time"></i>
            <span style="margin-left: 10px">{{ scope.row.create_time }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="work_status" label="工作状态" align="center">
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="150" align="center">
          <template slot-scope="scope">
            <el-tooltip class="item" effect="dark" content="编辑用户信息" placement="top">
              <el-button @click="handleClickModify(scope.row)" type="text" size="small">编辑</el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除用户" placement="top">
              <el-popconfirm title="确定将该用户删除吗？" @confirm="handleDeleteUser(scope.row.id)">
                <el-button  type="text" size="small" style="color: red;margin-left: 10px;" slot="reference">删除</el-button>
              </el-popconfirm>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="修改密码" placement="top">
              <el-button @click="handleClickModifyPassword(scope.row)" style="color: #ACB200;margin-left: 10px;"
                type="text" size="small">修改密码</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="pageRow">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="conditions.currentPage" :page-sizes="[5, 10, 15, 20]" :page-size="conditions.size"
        layout="total, sizes, prev, pager, next, jumper" :total="userList.total">
      </el-pagination>
    </div>

    <el-dialog :title="dialogInfo.title" :visible.sync="dialogVisible" width="40%" :before-close="handleClose">
      <el-row type="flex" class="row-bg" justify="space-around">
        <el-col :span="100">
          <el-avatar :size="80" v-if="dialogInfo.user.user_image"
            :src="dialogInfo.user.user_image"></el-avatar>
          <el-avatar :size="80" v-else
            src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg"></el-avatar>
        </el-col>
      </el-row>
      <el-row type="flex" class="row-bg dialogRow" justify="space-around">
        <el-col :span="10">
          <el-tag>账号:</el-tag>
          <el-input type="text" v-model="dialogInfo.user.username" maxlength="10" show-word-limit clearable
            :disabled="dialogInfo.title != '新增用户'"></el-input>
        </el-col>
        <el-col :span="10">
          <el-tag>工作状态:</el-tag>
          <el-select v-model="dialogInfo.user.work_status" clearable placeholder="请选择" style="width: 100%;">
            <el-option label="已工作" value="已工作"></el-option>
            <el-option label="未工作" value="未工作"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row type="flex" class="row-bg dialogRow" justify="space-around">
        <el-col :span="10">
          <el-tag type="success">姓名:</el-tag>
          <el-input type="text" placeholder="请输入姓名" v-model="dialogInfo.user.name" maxlength="10" show-word-limit
            clearable></el-input>
        </el-col>
        <el-col :span="10">
          <el-tag type="success">性别:</el-tag>
          <el-select v-model="dialogInfo.user.sex" clearable placeholder="请选择" style="width: 100%;">
            <el-option label="男" value="男"></el-option>
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-col>
      </el-row>
      <el-row type="flex" class="row-bg dialogRow" justify="space-around">
        <el-col :span="10">
          <el-tag type="info">年龄:</el-tag>
          <el-input type="number" placeholder="请输入年龄" v-model="dialogInfo.user.age" maxlength="2" show-word-limit
            clearable></el-input>
        </el-col>
        <el-col :span="10">
          <el-tag type="info">地址:</el-tag>
          <el-input type="text" placeholder="请输入地址" v-model="dialogInfo.user.address" maxlength="10" show-word-limit
            clearable></el-input>
        </el-col>
      </el-row>
      <el-row type="flex" class="row-bg dialogRow" justify="space-around">
        <el-col :span="10">
          <el-tag type="warning">电话:</el-tag>
          <el-input type="text" placeholder="请输入电话" v-model="dialogInfo.user.phone_number" maxlength="11" show-word-limit
            clearable></el-input>
        </el-col>
        <el-col :span="10">
          <el-tag type="warning">邮箱:</el-tag>
          <el-input type="text" placeholder="请输入邮箱" v-model="dialogInfo.user.email" maxlength="20" show-word-limit
            clearable></el-input>
        </el-col>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>

import { mapGetters } from 'vuex'

export default {
  name: 'UserTable',
  data() {
    return {
      conditions: {
        name: '',
        sex: '',
        work_status: '',
        currentPage: 1,
        size: 10
      },
      loading: false,
      dialogVisible: false,
      dialogInfo: {
        title: '',
        user: {}
      },
      errorMsg: ''
    }
  },
  computed: {
    ...mapGetters(['userList'])
  },
  async created() {
    await this.getList(this.conditions)
  },
  methods: {
    /**
     * 模糊查询
     */
    search() {
      this.getList(this.conditions)
    },

    reset() {
      this.conditions = {
        name: '',
        sex: '',
        work_status: '',
        currentPage: 1,
        size: 10
      }
      this.search()
    },

    tableRowClassName({ row, rowIndex }) {
      if (row.work_status === '已工作') {
        return 'success-row';
      }
      return '';
    },

    getList(conditions) {
      this.loading = true
      this.$store.dispatch('manage/queryUserList', conditions)
      /**
      * 保证数据一致性 可能存在刷新网页数据丢失的问题
      */
      this.userList.length === 0 ? this.userList = JSON.parse(sessionStorage.getItem('userList')) : this.userList
      setTimeout(() => {
        this.loading = false
      }, 1000);

    },

    /**
     * 删除用户
     * @param {*} id
     */
    handleDeleteUser(id) {
      this.$store.dispatch('manage/deleteUserById', id)
        .then(resp => {
          const { data } = resp.data
          if (data) this.$message.success('用户删除成功')
          else this.$message.error('用户删除失败,请联系管理员')
        })
        .catch(error => this.$message.error(error))
        .finally(() => this.getList(this.conditions))
    },

    handleSizeChange(val) {
      this.conditions.size = val
      this.getList(this.conditions)
    },

    handleCurrentChange(val) {
      this.conditions.currentPage = val
      this.getList(this.conditions)
    },

    /**
     * 修改用户信息
     * @param {*} row
     */
    handleClickModify(row) {
      this.dialogInfo.title = '编辑用户信息'
      this.dialogInfo.user = row
      this.dialogVisible = !this.dialogVisible
    },

    insert() {
      this.dialogInfo.title = '新增用户'
      this.dialogVisible = !this.dialogVisible
    },

    closeDialog() {
      this.dialogInfo.title = ''
      this.dialogInfo.user = {}
      this.dialogVisible = false;
    },

    submitUser() {
      const { title } = this.dialogInfo
      const { age } = this.dialogInfo.user
      if (age < 0 || age > 100) this.$message.error('妖怪是不能用这平台的')

      this.loading = false
      if (title === '编辑用户信息') {
        this.$store.dispatch('manage/modifyUserInfo', this.dialogInfo.user)
          .then(resp => {
            if (resp.data) this.$message.success('用户修改成功')
            else this.$message.error('用户修改失败,请联系管理员')
          })
          .catch(error => this.$message.error(error))
          .finally(() => {
            this.getList(this.conditions)
            this.dialogVisible = false
          })
      } else {
        this.$prompt('请输入该账号密码', '提示')
          .then(({ value }) => {
            this.$store.dispatch('manage/saveNewUser', { ...this.dialogInfo.user, password: value })
              .then(resp => {
                if (resp.data) this.$message.success('添加新用户成功')
                else this.$message.error('用户新增失败,请联系管理员')
              })
              .catch(error => this.$message.error(error))
              .finally(() => {
                this.getList(this.conditions)
                this.dialogVisible = false
              })
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '取消输入'
            });
          });
      }
    },

    handleClose() {
      this.closeDialog()
    },

    open2() {
      this.$notify({
        title: '提示',
        message: '暂时不知道这个按钮该干嘛',
        position: 'bottom-right'
      });
    },

    /**
    * 修改用户信息
    * @param {*} row
    */
    handleClickModifyPassword(row) {
      this.$prompt('请输入新的密码', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
      }).then(({ value }) => {
        this.$store.dispatch('manage/modifyPassword', { id: row.id, password: value })
          .then(resp => {
            if (resp.data) this.$message.success('修改用户密码成功')
            else this.$message.error('修改用户密码失败,请联系管理员')
          })
          .catch(error => this.$message.error(error))
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消输入'
        });
      });
    },
  },
}
</script>

<style lang="css">
.tableRow,
.pageRow,
.dialogRow {
  margin-top: 15px;
}

.pageRow {
  display: flex;
  justify-content: center;
}

.el-table .success-row {
  background: #f0f9eb;
}

.search-input {
  width: 220px;
}

.search-select {
  width: 180px;
  margin-left: 15px;
}

.search-button {
  margin-left: 15px;
}

/*
@media screen and (max-width: 440px) {
  .app-container el-dialog {
    width: 100%;
  }
} */
</style>
